import { Component, OnInit, OnDestroy } from '@angular/core'
import { NzMessageService } from 'ng-zorro-antd'
import { ActivatedRoute, Router } from '@angular/router'
import { Location } from '@angular/common'

import { UserStoreService } from '../user-store.service'
import { INewPageColumn } from '@shared/interfaces/common'
import { PageService } from '@shared/services/page.service'
import { UserService } from '../user.service'
import { ComWindow } from '@shared/classes/ComWindowClass'
import { UserNewUserComponent } from './user/user.component'
import { ICreateUserForm } from '@shared/interfaces/user'
import { I18NService } from '@core'

@Component({
  selector: 'app-user-new',
  templateUrl: './new.component.html',
})
export class UserNewComponent implements OnInit, OnDestroy {
  pages: INewPageColumn[] = []

  constructor(
    public msg: NzMessageService,
    public router: Router,
    public route: ActivatedRoute,
    private userStore: UserStoreService,
    private userService: UserService,
    private pageService: PageService,
    private location: Location,
    private i18n: I18NService,
  ) {}

  ngOnInit(): void {
    this.initColumns()
  }

  ngOnDestroy(): void {
    this.userStore.reset()
  }

  initColumns() {
    this.pages = [
      {
        component: new ComWindow(UserNewUserComponent, { title: this.trans('GENERAL.INFO.OTHER.USERS') }),
      },
    ]
  }

  submit(): void {
    const user = this.userStore.value
    const reqUser = user as ICreateUserForm

    this.userService.create(reqUser).subscribe(data => {
      if (Object.keys(data).length !== 0) {
        this.pageService.triggerGuardAlive(false)
        this.msg.success(this.trans('GENERAL.NOTIFICATION.CREATE_SUCCESS'))
        this.location.back()
      } else {
        this.msg.error(this.trans('GENERAL.NOTIFICATION.CREATE_FAIL'))
      }
    })
  }

  trans(key: string, params?: Object): string {
    return this.i18n.fanyi(key, params)
  }
}
